﻿var appAjax = {

	xhrErrorCode: -65535,

	initialize: function () {
		$(document).bind("ajaxStart", function () { appAjax.loader(true) }).bind("ajaxStop", function () { appAjax.loader(false) });
	},

	//below is not used. If a call fails, an error is displayed.
	checkConnection: function () {
		if (navigator) {
			if (navigator.connection) {
				var networkState = navigator.connection.type;
				if (networkState == Connection.NONE) {
					//futur use.
				}
			}
		}
	},

    call: function (props) {
        $.support.cors = true;
        $.mobile.allowCrossDomainPages = true;

        $.ajax({
            type: "POST",
            url: props.url,
            data: JSON.stringify(props.data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
			cache: false,
			timeout: props.timeout,
			success: function (msg) {appAjax.ajaxSuccess(msg, props.successHandler, props.failedHandler); },
			error: function (xhr, status, error) { appAjax.ajaxError(xhr, status, error, props.failedHandler); }
        });
    },

    ajaxSuccess: function (msg, s, e) {
    	if (msg.d.ErrorCode != '0') {
    		if (typeof e !== 'undefined') e({ success: false, errorCode: msg.d.ErrorCode, errorMessage: msg.d.ErrorMessage });
    	} else if (typeof s !== 'undefined') s(msg);
    },

    ajaxError: function (xhr, status, error, e) {
    	if (typeof e !== 'undefined') {
    		var err;
    		try {
    			err = JSON.parse(xhr.responseText);
    		}
    		catch (exc) {
    			err = { Message: xhr.responseText };
    		}
    		e({ success: false, errorCode: this.xhrErrorCode, errorMessage: err.Message.length == 0 ? 'Kan geen verbinding maken met de server' : err.Message });
    	}
    },

	loader: function (show) {
		if (show) {
			$.mobile.loading('show', {
				text: 'laden...',
				textVisible: true,
				theme: 'a',
				textonly: false,
				html: ''
			});
		}
		else $.mobile.loading('hide');
	}
};